package com.open.party.cloud.view.examine

import android.os.Bundle
import android.view.View
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusRecycleViewTitleBaseActivity
import cn.sinothk.map.amap.base.MapCallback
import cn.sinothk.map.amap.location.AMapLocate
import cn.sinothk.map.amap.location.AMapLocationEntity
import com.open.party.cloud.R
import com.open.party.cloud.model.*
import com.open.party.cloud.model.data.LocalCache
import com.open.party.cloud.view.examine.adapter.ExamineAttendanceCourseListAdapter
import com.open.party.cloud.viewModel.ExamineViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.android.utils.inters.OnSuperListener
import com.sinothk.rxretrofit.bean.PageVo
import kotlinx.android.synthetic.main.activity_load_recycle_view_load_tip_shadow_for_attendance.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.text.SimpleDateFormat
import java.util.*

class ExamineClassDoAttendanceListActivity : AppEventBusRecycleViewTitleBaseActivity<MsgVo>(), OnSuperListener<ExamineAttendanceCourseEntity> {
    var attendanceVO = AttendanceVO()
    var classId: String? = null
    var viewModel: ExamineViewModel? = null
    private var adapter: ExamineAttendanceCourseListAdapter? = null

    var thread: Thread? = null

    private fun initTimer() {
        val format = SimpleDateFormat("HH:mm:ss")
        currTimeTv.text = format.format(Date())

        thread = Thread {
            Thread.sleep(1000)
            do {
                try {
                    Thread.sleep(1000)
                    runOnUiThread {
                        currTimeTv.text = format.format(Date())
                    }
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            } while (true)

        }
        thread?.start()
    }

    private fun doAttendance() {
        attendanceVO.userId = LocalCache.getLoginUserId()

        if (XUtils.string().isEmpty(attendanceVO.schId)) {
            XUtils.toast().show("请选择签到课程")
            return
        }

        if (XUtils.string().isEmpty(attendanceVO.schId)) {
            XUtils.toast().show("请选择签到课程")
            return
        }

        if (XUtils.string().isEmpty(attendanceVO.address)) {
            XUtils.toast().show("获取位置失败，请检查后重试")
            return
        }

        showLoadingDialog("正在提交")
        viewModel?.doAttendance(attendanceVO)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<AttendanceEntity>) {
        if (result.eventType != "doAttendance") {
            return
        }

        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    XUtils.toast().show("打开成功")
//                    if ("sign" == attendanceVO.checkType) {
//                        signTimeTv.text = XUtils.string().getNotNullValue(result.data.createTime)
//                    } else {
//                        outTimeTv.text = XUtils.string().getNotNullValue(result.data.createTime)
//                    }

                    viewModel!!.getSchoolAttendanceList(classId!!)
                } else {
                    XUtils.toast().show(result.msg)
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun attendanceListCallback(result: ResultInfo<List<AttendanceEntity>>) {
        if ("getSchoolAttendanceList" != result.eventType) {
            return
        }

        when (result.code) {
            ResultInfo.SUCCESS -> {
                attendanceDisable()

//                if (result.data == null || result.data.isEmpty()) {
//                } else if (result.data.size == 1) {
//                    showTimeInfo(result.data)
//                } else {
//
////                    showTimeInfo(result.data)
//                }
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

    private fun showSign() {
//        localInfoItem.visibility = View.VISIBLE
//
//        attendanceVO.checkType = "sign"
//        currTypeTv.text = "签到"
//        signItem.setBackgroundResource(R.drawable.selector_bg_attendance)
//        signFlag.setTextColor(ContextCompat.getColor(this, R.color.white))
//        signTimeTv.setTextColor(ContextCompat.getColor(this, R.color.white))
//
//        outItem.setBackgroundResource(R.color.app_bg)
//        outFlag.setTextColor(ContextCompat.getColor(this, R.color.page_title))
//        outTimeTv.setTextColor(ContextCompat.getColor(this, R.color.page_sub))
    }

    private fun showOut() {
//        localInfoItem.visibility = View.VISIBLE
//
//        attendanceVO.checkType = "out"
//        currTypeTv.text = "签退"
//
//        signItem.setBackgroundResource(R.color.app_bg)
//        signFlag.setTextColor(ContextCompat.getColor(this, R.color.page_title))
//        signTimeTv.setTextColor(ContextCompat.getColor(this, R.color.page_sub))
//
//        outItem.setBackgroundResource(R.drawable.selector_bg_attendance)
//        outFlag.setTextColor(ContextCompat.getColor(this, R.color.white))
//        outTimeTv.setTextColor(ContextCompat.getColor(this, R.color.white))
    }

    private fun attendanceDisable() {
        doAttendanceItem.isClickable = false
        currTypeTv.text = "已打卡"
        localInfoItem.visibility = View.GONE
        refreshData()
    }

//    private fun showTimeInfo(attendanceList: List<AttendanceEntity>) {
//        for (attendance in attendanceList) {
////            if ("sign" == attendance.checkType) {
////                signTimeTv.text = XUtils.string().getNotNullValue(attendance.createTime)
////            } else {
////                outTimeTv.text = XUtils.string().getNotNullValue(attendance.createTime)
////            }
//        }
//    }

    private fun initView() {
        initTimer()

        AMapLocate().locationOnce(this, object : MapCallback<AMapLocationEntity> {
            override fun onFail(msg: String?) {
                runOnUiThread {
                    XUtils.toast().show(msg)
                }
            }

            override fun onSuccess(mapInfo: AMapLocationEntity) {
                attendanceVO.lat = mapInfo.latitude
                attendanceVO.lng = mapInfo.longitude
                attendanceVO.address = mapInfo.address
                addressTv.text = XUtils.string().getNotNullValue(mapInfo.address)
            }
        })

        // 签到类型
        attendanceVO.checkType = "sign"
    }

    override fun onDestroy() {
        super.onDestroy()
        thread = null
    }

    override fun getLayoutResId(): Int = R.layout.activity_load_recycle_view_load_tip_shadow_for_attendance

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        classId = intent.getStringExtra("classId")
        setViewTitle("签到打卡", "签到记录") {
            XUtils.intent().openActivity(this@ExamineClassDoAttendanceListActivity, ExamineAttendanceHistoryListActivity::class.java)
                .putStringExtra("classId", classId).start()
        }

        viewModel = ExamineViewModel()
        attendanceVO.classId = classId
        initView()
        initView2()
//        viewModel!!.getSchoolAttendanceList(classId!!)

        doAttendanceItem.setOnClickListener {
            doAttendance()
        }


        loadingTipView.setRetryListener {
            loadingTipView.showLoading("努力加载中")
            refreshData()
        }

        loadingTipView.showLoading("努力加载中")
        refreshData()
    }

    private fun initView2() {
        initRecycleLinearView(loadingRecyclerView)

        adapter = ExamineAttendanceCourseListAdapter(this)
        loadingRecyclerView.adapter = adapter
        adapter?.setOnSuperListener(this)
        loadingRecyclerView.setLoadingMoreEnabled(false)

        loadingTipView.setRetryListener {
            loadingTipView.showLoading("努力加载中")
            refreshData()
        }

        loadingTipView.showLoading("努力加载中")
        refreshData()
    }

    override fun loadData(pageVo: PageVo<MsgVo>) {
//        val pageReq = PageReq<MsgVo>()
//        pageReq.pageNo = pageVo.pageNum
//        pageReq.pageSize = pageVo.pageSize
//        pageReq.data = MsgVo()
        viewModel!!.getSchoolCourseCourseList(classId!!)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun listEventBusCallback(result: ResultInfo<List<ExamineAttendanceCourseEntity>>) {

        if ("getSchoolCourseCourseList" != result.eventType) {
            return
        }

        stopLoading(loadingRecyclerView, loadType)

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    if (result.data.isEmpty()) {
                        loadingTipView.showEmpty("暂无打卡课程", R.drawable.empty_nodata)
                        loadingRecyclerView.setLoadingMoreEnabled(false)
                        hideAttendanceView()
                    } else {
                        attendanceCourseList = result.data!!
                        adapter!!.setData(attendanceCourseList)
                        loadingTipView.showContent()
                        showAttendanceView()
                    }
                } else {
                    loadingTipView.showError("数据异常")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                loadingTipView.showError("Token过期，请重新登录")
            }
            else -> {
                loadingTipView.showError(result.msg)
            }
        }
    }

    private fun showAttendanceView() {
        bottomView.visibility = View.VISIBLE
        localInfoItem.visibility = View.VISIBLE
    }

    private fun hideAttendanceView() {
        bottomView.visibility = View.GONE
    }

    var attendanceCourseList: List<ExamineAttendanceCourseEntity>? = null

    override fun onClick(position: Int, itemData: ExamineAttendanceCourseEntity, flag: String?) {
        attendanceVO.schId = XUtils.string().getNotNullValue(itemData.schId)
        attendanceVO.courseId = XUtils.string().getNotNullValue(itemData.id)
        attendanceVO.courseName = XUtils.string().getNotNullValue(itemData.courseName)

        for (index in attendanceCourseList!!.indices) {
            attendanceCourseList!![index].isHasSelected = false
        }
        attendanceCourseList!![position].isHasSelected = true

        adapter!!.setData(attendanceCourseList)
    }
}